import { createRouter, createWebHistory } from 'vue-router'
import { isAuthenticated, hasPermission } from '@/utils/auth'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/auth/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'home',
    component: () => import('../views/home/Home.vue'),
    meta: {
      title: '首页',
      isHome: true,
      requiresAuth: true
    }
  },
  {
    path: '/apps',
    name: 'apps',
    component: () => import('../views/apps/AppList.vue'),
    meta: {
      title: 'RPA应用管理',
      requiresAuth: true,
      permissions: ['app:view']
    }
  },
  {
    path: '/tasks',
    name: 'tasks',
    component: () => import('../views/tasks/TaskList.vue'),
    meta: {
      title: 'RPA运行管理',
      requiresAuth: true,
      permissions: ['task:view']
    }
  },
  {
    path: '/robots',
    name: 'robots',
    component: () => import('../views/robots/RobotList.vue'),
    meta: {
      title: 'RPA机器人管理',
      requiresAuth: true,
      permissions: ['robot:view']
    }
  },
  {
    path: '/users',
    name: 'users',
    component: () => import('../views/auth/UserRoles.vue'),
    meta: {
      title: '用户管理',
      requiresAuth: true,
      permissions: ['*'] // 只有管理员可以访问
    }
  },
  {
    path: '/roles',
    name: 'roles',
    component: () => import('../views/auth/RoleManagement.vue'),
    meta: {
      title: '角色管理',
      requiresAuth: true,
      permissions: ['*'] // 只有管理员可以访问
    }
  },
  {
    path: '/organizations',
    name: 'organizations',
    component: () => import('../views/auth/OrganizationManagement.vue'),
    meta: {
      title: '组织管理',
      requiresAuth: true,
      permissions: ['*'] // 只有管理员可以访问
    }
  },
  {
    path: '/403',
    name: 'forbidden',
    component: () => import('../views/auth/Forbidden.vue'),
    meta: {
      title: '权限不足',
      requiresAuth: false
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('../views/NotFound.vue'),
    meta: {
      title: '页面不存在',
      requiresAuth: false
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - RPA管理系统` : 'RPA管理系统'
  
  // 检查是否需要认证
  if (to.meta.requiresAuth && !isAuthenticated()) {
    ElMessage.warning('请先登录')
    next('/login')
    return
  }
  
  // 检查权限
  if (to.meta.permissions) {
    const hasRequiredPermission = to.meta.permissions.some(permission => hasPermission(permission))
    if (!hasRequiredPermission) {
      ElMessage.error('您没有权限访问该页面')
      next('/403')
      return
    }
  }
  
  next()
})

export default router 